package com.bluse.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


@Component(value = "httpClientConfigClient")
public class HttpClient {

    private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

    private HttpHeaders headers;

    private RestTemplate restTemplate;

    public HttpClient() {
        this.headers = new HttpHeaders();
        headers.set("appKey", "fx_appKey234");
        headers.set("appSecret", "fx_appSecret234");

        this.restTemplate = new RestTemplate();
    }

    /**
     * getMethod
     *
     * @param responseType
     * @param <T>
     * @return
     */
    public <T> T getMethod(Class<T> responseType, String uri) {
        //httoEntity
        HttpEntity<T> entity = new HttpEntity<T>(headers);
        //restTemplate
        ResponseEntity<T> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, entity, responseType);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            logger.info("Response Body:{}", responseEntity.getBody());
        }
        return responseEntity.getBody();
    }


    /**
     * PostMethod
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T postMethod(Class<T> tClass, Map<String, Object> requestBody, String uri) throws HttpRequestMethodNotSupportedException {

        //RequestEntity
        HttpEntity entity = new HttpEntity(requestBody, headers);
        //RestTemplate
        ResponseEntity<T> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, entity, tClass);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new HttpRequestMethodNotSupportedException("get", "Request credit  api failed!");
        }
        logger.info("Response Body:{}", responseEntity.getBody());
        return responseEntity.getBody();
    }


}
